/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/Exceptions.hpp"
#include "IBulletShape.hpp"
#include "PhysicRegion.hpp"
#include "RigidBody.hpp"

namespace XernBullet
{
	// This class is copied verbatim from bullet physics source code(btKinematicCharacterController.cpp)
	class btKinematicClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback
	{
	public:
		btKinematicClosestNotMeConvexResultCallback (btCollisionObject* me) : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
		{
			m_me = me;
		}

		virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult,bool normalInWorldSpace)
		{
			if (convexResult.m_hitCollisionObject == m_me)
				return 1.0;

			return ClosestConvexResultCallback::addSingleResult (convexResult, normalInWorldSpace);
		}
	protected:
		btCollisionObject* m_me;
	};

	PhysicRegion::PhysicRegion(btDynamicsWorld *world)
		: world(world)
	{
	}

	PhysicRegion::~PhysicRegion()
	{
	}

	void PhysicRegion::AddRigidBody(boost::shared_ptr<IRigidBody> body)
	{
		boost::shared_ptr<RigidBody> rbody =
				boost::dynamic_pointer_cast<RigidBody> (body);
		if(!rbody)
			throw XernException("Invalid rigid body.");
		world->addRigidBody(rbody->GetBulletBody());
	}

	void PhysicRegion::RemoveRigidBody(boost::shared_ptr<IRigidBody> body)
	{
		boost::shared_ptr<RigidBody> rbody =
				boost::dynamic_pointer_cast<RigidBody> (body);
		if(!rbody)
			throw XernException("Invalid rigid body.");
		world->removeRigidBody(rbody->GetBulletBody());
	}

	void PhysicRegion::AddAction(boost::shared_ptr<IRigidBody> body)
	{
		boost::shared_ptr<RigidBody> rbody =
				boost::dynamic_pointer_cast<RigidBody> (body);
		if(!rbody)
			throw XernException("Invalid rigid body.");
		world->addAction(rbody.get());
	}

	void PhysicRegion::RemoveAction(boost::shared_ptr<IRigidBody> body)
	{
		boost::shared_ptr<RigidBody> rbody =
				boost::dynamic_pointer_cast<RigidBody> (body);
		if(!rbody)
			throw XernException("Invalid rigid body.");
		world->removeAction(rbody.get());
	}

	class RegionRayCallback: public btCollisionWorld::ClosestRayResultCallback
	{
	public:
		RegionRayCallback()
			: btCollisionWorld::ClosestRayResultCallback(btVector3(0,0,0), btVector3(0,0,0))
		{
			ignore = NULL;
		}

		virtual	btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
		{
			if(rayResult.m_collisionObject == ignore)
				return 1.0;
			return ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
		}

		btCollisionObject *ignore;
	};

	RayCastResult
	PhysicRegion::CastRay(const Vector3 &start, const Vector3 &end) const
	{
		return CastRay(start, end, boost::shared_ptr<IRigidBody> ());
	}

	RayCastResult
	PhysicRegion::CastRay(const Vector3 &start, const Vector3 &end,
			boost::shared_ptr<IRigidBody> ignore) const
	{

		RayCastResult res;
		btVector3 bStart(start.x, start.y, start.z);
		btVector3 bEnd(end.x, end.y, end.z);
		RegionRayCallback callback;
		if(ignore)
		{
			boost::shared_ptr<RigidBody> body = boost::dynamic_pointer_cast<RigidBody> (ignore);
			if(body)
				callback.ignore = body->GetBulletBody();
		}

		// Perform the ray test.
		world->rayTest(bStart, bEnd, callback);

		// Read the callback.
		if(callback.hasHit())
		{
			res.fraction = callback.m_closestHitFraction;
			btCollisionObject *object = callback.m_collisionObject;
			if(object)
			{
				RigidBody *other = static_cast<RigidBody*> (object->getUserPointer());
				if(other)
					res.firstObject = other->GetSelf();
			}
		}
		else
		{
			res.fraction = -1.0;
		}

		return res;
	}

	inline void ConvertTransform(btTransform &dest, const Transform &trans)
	{
		const Vector3 &pos = trans.GetVector();
		const Quaternion &rot = trans.GetRotation();
		dest.setOrigin(btVector3(pos.x, pos.y, pos.z));
		dest.setRotation(btQuaternion(rot.x, rot.y, rot.z, rot.w));
	}

	inline Vector3 InterpolateVector(const Vector3 &a, const Vector3 &b, float fraction)
	{
		return (1.0f-fraction)*a + fraction*b;
	}

	float PhysicRegion::MoveObject(boost::shared_ptr<IRigidBody> object, const Transform &from, const Transform &to) const
	{
		// Cast the object
		boost::shared_ptr<RigidBody> rbody =
				boost::dynamic_pointer_cast<RigidBody> (object);
		if(!rbody)
			throw XernException("Invalid rigid body.");

		// Get the collision shape.
		boost::shared_ptr<ICollisionShape> shape = object->GetCollisionShape();
		if(!shape)
		{
			object->SetTransform(to);
			return 1.0f;
		}

		// Get the collision shape.
		boost::shared_ptr<IBulletShape> bshape =
				boost::dynamic_pointer_cast<IBulletShape> (shape);
		if(!bshape)
			throw XernException("Expected bullet collision shape.");

		// Get the actual collision shape.
		btCollisionShape *ashape = bshape->GetBulletShape();
		if(!ashape)
			return 0.0;

		// Convert the transforms.
		btTransform bfrom, bto;
		ConvertTransform(bfrom, from);
		ConvertTransform(bto, to);

		// Perform the collision test.
		float fraction = 0.0f;
		if(ashape->isConvex())
		{
			btKinematicClosestNotMeConvexResultCallback result(rbody->GetBulletBody());

			world->convexSweepTest(static_cast<btConvexShape*> (ashape), bfrom, bto, result);
			fraction = result.m_closestHitFraction;
		}

		// Create the result transform.
		OrthoTransform res;
		res.SetVector(InterpolateVector(from.GetVector(), to.GetVector(), fraction));
		res.SetMatrix(to.GetMatrix()); // TODO: Interpolate rotation.
		object->SetTransform(res);
		return fraction;
	}
}; // namespace XernBullet
